let currentCaptchaId = null
let moveBtn = $("#slider-move-btn")

let successCallback
let failCallback
let closeCallback
let validateUrl
let initUrl

function init(options) {
    $('.slider').hide()
    clearAllPreventDefault($(".slider"))

    let {success, fail, checkUrl, generateUrl, close} = options
    validateUrl = checkUrl
    initUrl = generateUrl
    successCallback = success
    failCallback = fail
    closeCallback = close

    // 初始化
    $("#slider-close-btn").click(() => {
        closeCallback && closeCallback()
    })
    $("#slider-refresh-btn").click(() => {
        refreshCaptcha()
    })
    moveBtn.mousedown(down)
    moveBtn.on("touchstart", down)
}

function doDown() {
    moveBtn.css("background-position", "-5px 31.0092%")
}

function doMove(config) {
    const moveX = config.moveX;
    moveBtn.css("transform", "translate(" + moveX + "px, 0px)")
    $("#slider-img-div").css("background-position-x", moveX + "px");
}

function valid(captchaConfig) {
    let data = {
        bgImageWidth: captchaConfig.bgImageWidth,
        bgImageHeight: captchaConfig.bgImageHeight,
        sliderImageWidth: captchaConfig.sliderImageWidth,
        sliderImageHeight: captchaConfig.sliderImageHeight,
        startSlidingTime: captchaConfig.startTime,
        entSlidingTime: captchaConfig.stopTime,
        trackList: captchaConfig.trackArr
    };
    $.ajax({
        type: "POST",
        url: validateUrl + "?id=" + currentCaptchaId,
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify(data),
        success: function (res) {
            if (res) {
                successCallback && successCallback()
            } else {
                refreshCaptcha();
                failCallback && failCallback()
            }
        }
    })
}

function refreshCaptcha() {
    $('.slider').show()
    $.get(initUrl).done(
        function (data) {
            reset();
            currentCaptchaId = data.id;
            const bgImg = $(".bg-img-div");
            const sliderImg = $(".slider-img-div");

            bgImg.css("background-image", "url(" + data.captcha.backgroundImage + ")");
            sliderImg.css("background-image", "url(" + data.captcha.backgroundImage + ")");
            sliderImg.css("background-position", "0px 0px");
            let backgroundImageHeight = data.captcha.backgroundImageHeight;
            let height = ((backgroundImageHeight - data.captcha.data) / backgroundImageHeight) * 159;
            sliderImg.css("height", height);

            initConfig(bgImg.width(), bgImg.height(), sliderImg.width(), sliderImg.height(), 206);
        }
    )
}


function reset() {
    moveBtn.css("background-position", "-5px 11.79625%")
    moveBtn.css("transform", "translate(0px, 0px)")
    $(".rotate-img-div").css("transform", "rotate(0deg)")
    currentCaptchaId = null;
}
